public class Answer2 {
    //两个链表的第一个公共结点
    //https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&ru=/exam/oj
    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
    // 解法一： 常规
    public ListNode FindFirstCommonNode1(ListNode pHead1, ListNode pHead2) {
        ListNode cur1 = pHead1;
        int len1 = 0;
        ListNode cur2 = pHead2;
        int len2 = 0;
        while (cur1 != null) {
            len1++;
            cur1 = cur1.next;
        }
        while (cur2 != null) {
            len2++;
            cur2 = cur2.next;
        }
        if (len1 > len2) {
            int len = len1 - len2;
            cur1 = pHead1;
            while (len-- != 0) {
                cur1 = cur1.next;
            }
            cur2 = pHead2;
            while (cur1 != cur2) {
                cur1 = cur1.next;
                cur2 = cur2.next;
            }
        } else {
            int len = len2 - len1;
            cur2 = pHead2;
            while (len-- != 0) {
                cur2 = cur2.next;
            }
            cur1 = pHead1;
            while (cur1 != cur2) {
                cur1 = cur1.next;
                cur2 = cur2.next;
            }
        }
        return cur1;
    }
    // 解法二： 利用等量关系： x1+x+x2=x2+x+x1
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode cur1=pHead1;
        ListNode cur2=pHead2;

        while(cur1 != cur2){

            cur1= cur1 != null ?cur1.next : pHead2;
            cur2= cur2 != null ?cur2.next : pHead1;
        }

        return cur1;
    }
}
